package com.example.a828502.networkresourcetest;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    private ImageView imageView;
    private Bitmap bitmap = null;
    private Button mBtn;
    private String url = "https://www.baidu.com/img/bd_logo1.png"; // 开启一个子线程，进行网络操作，等待有返回结果，使用handler通知UI

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView)findViewById(R.id.imageView);
        mBtn = (Button)findViewById(R.id.button);

        mBtn.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new Thread(networkTask).start();

            }
        });



    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("value");
            Log.i("mylog", "请求结果为-->" + val);
            // TODO
            imageView.setImageBitmap(bitmap);
            savePicture(bitmap);


            // UI界面的更新等相关操作
        }
    };
    /**
     * 网络操作相关的子线程
     */
    Runnable networkTask = new Runnable() {

        @Override
        public void run() {
            // TODO
            // 在这里进行 http request.网络请求相关操作
            Message msg = new Message();
            try {

                //字节形式返回
//                byte[] data = ImageService.getImage(url);
//                bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);  //生成位图

                //Stream形式返回
                URL pictureUrl = new URL(url);
                //第一种
//                InputStream in = pictureUrl.openStream();
                //第二种
//                URLConnection con = pictureUrl.openConnection();
//                InputStream in = con.getInputStream();
                //第三种

                HttpURLConnection con = (HttpURLConnection) pictureUrl.openConnection();
                InputStream in = con.getInputStream();

                bitmap = BitmapFactory.decodeStream(in);
            } catch (IOException e) {
                Toast.makeText(MainActivity.this, "出错了", Toast.LENGTH_LONG).show();  //通知用户连接超时信息
                Log.i("错误", e.toString());
            }
            Bundle data = new Bundle();
            data.putString("value", "请求结果成功");
            msg.setData(data);
            handler.sendMessage(msg);
        }
    };

    public void savePicture(Bitmap bitmap)  {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))   {
            try {
                File sdcardDir = Environment .getExternalStorageDirectory();
                String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + "baidu.jpg";
                String filename = sdcardDir.getCanonicalPath()+ "/DCIM/Camera/"  +name;



                File file = new File(filename);
                FileOutputStream out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                out.flush();
                out.close();
                Toast.makeText(this,"图片显示并保存成功",Toast.LENGTH_LONG).show();
            }
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }
            catch (IOException e)   {
                e.printStackTrace();
            }
        }
    }

}


